import { message } from 'antd';
import { list, create, edit, dele, upload } from '../services/image';

export default {
  namespace: 'image',

  state: {
    data: [],
    total: 0,
    success: true,
    uploadUrl: '', // 文件上传成功后返回的网络地址
  },

  effects: {
    *list({ payload }, { call, put }) {
      const response = yield call(list, payload);
      yield put({ type: 'callbackList', response });
    },
    *create({ payload }, { call, put }) {
      const response = yield call(create, payload);
      yield put({ type: 'callbackSave', response });
    },
    *edit({ payload }, { call, put }) {
      const response = yield call(edit, payload);
      yield put({ type: 'callbackSave', response });
    },
    *dele({ payload }, { call, put }) {
      const response = yield call(dele, payload);
      yield put({ type: 'callbackSave', response });
    },
    *upload({ payload }, { call, put }) {
      const response = yield call(upload, payload);
      yield put({ type: 'callbackUpload', response });
    },
  },

  reducers: {
    callbackList(st, { response }) {
      const state = st;
      if (response.success) {
        state.data = response.root.sort((a, b) => b.sequ - a.sequ);
        state.total = response.total;
      }
      return { ...state };
    },
    callbackSave(st, { response }) {
      const state = st;
      state.success = response.success;
      if (response.success) message.success(response.msg);
      return { ...state };
    },
    callbackUpload(st, { response }) {
      const state = st;
      state.success = response.success;
      if (response.success) state.uploadUrl = response.imageUrl;
      return { ...state };
    },
  },
};
